import { login, logout, getInfo } from '@/api/account'
import { getToken, setToken, removeToken, setRefreshToken, getRefreshToken, setUserKey, removeUserKey } from '@/utils/auth'
import { localstore } from '@/utils/util'

const account = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    storehouses: [],
    currentStorehouse: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ENTITYNAME: (state, entityName) => {
      state.entityName = entityName
    },
    SET_STOREHOUSES: (state, storehouses) => {
      state.storehouses = storehouses
    },
    SET_CURRENT_STOREHOUSE: (state, storehouse) => {
      state.currentStorehouse = storehouse
    },
    SET_ACCOUNTID: (state, accountId) => {
      state.accountId = accountId
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const userKey = userInfo.userKey.trim()
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('username', userKey)
        formData.append('password', userInfo.password)
        formData.append('grant_type', 'password')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')

        login(formData).then(response => {
          setToken(response.access_token, response.expires_in)
          setUserKey(response.username, response.expires_in)
          setRefreshToken(response.refresh_token)
          commit('SET_TOKEN', response.access_token)
          commit('SET_ACCOUNTID', response.accountId)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // ServiceTicket 登录
    LoginServiceTicket({ commit }, serviceTicket) {
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('username', '')
        formData.append('password', '123456')
        formData.append('grant_type', 'password')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        formData.append('auth_type', '3PL')
        formData.append('serviceTicket', serviceTicket)
        login(formData).then(response => {
          if (response.access_token) {
            setToken(response.access_token, response.expires_in)
            // setToken(response.access_token, 10)
            setUserKey(response.username, response.expires_in)
            // 设置刷新token
            setRefreshToken(response.refresh_token)
            commit('SET_TOKEN', response.access_token)
            commit('SET_ACCOUNTID', response.accountId)
            resolve()
          } else {
            // 登录失败
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 刷新token
    RefreshToken({ commit }) {
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('grant_type', 'refresh_token')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        formData.append('refresh_token', getRefreshToken())
        login(formData).then(response => {
          console.log('获取到了刷新token')
          if (response.access_token) {
            setToken(response.access_token, response.expires_in)
            setRefreshToken(response.refresh_token)
            commit('SET_TOKEN', response.access_token)
            resolve()
          } else {
            // 刷新token失败
            setToken('')
            setRefreshToken('')
            commit('SET_TOKEN', '')
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 免费注册
    Register({ commit }) {
      return new Promise((resole, reject) => {
        const register = '123'
        setToken(register)
        commit('SET_TOKEN', register)
        resole()
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.userName)
          commit('SET_AVATAR', data.avatar)
          commit('SET_ENTITYNAME', data.entityName)
          commit('SET_STOREHOUSES', data.storehouses)
          commit('SET_CURRENT_STOREHOUSE', data.storehouses[0])
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeUserKey()
          removeToken()
          localstore('visitedViews', null)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeUserKey()
        removeToken()
        localstore('visitedViews', null)
        resolve()
      })
    }
  }
}

export default account
